package com.ccl.iot.device;

import android.graphics.Bitmap;

import com.ccl.iot.IOTNetAPIEnum;
import com.ccl.iot.IOTObject;
import com.ccl.iot.R;
import com.ccl.iot.dvr.utils.LoggerUtil;
import com.ccl.iot.managers.ImageManager;
import com.ccl.iot.object.IOTDeviceInfoEx;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import static com.ccl.iot.dvr.utils.DVRUtil.zoneIndex;


public class IOTProbe extends IOTDeviceWithState implements IOTObject.IOTDVRInner {

    //已经创建的探头集合
    private Map<Integer, SingleProbe> mProbes = new TreeMap<Integer, SingleProbe>();

    //	TreeMap<Integer, String> mm = new TreeMap<Integer, String>();

    private static final int BASEADDRESS = 24;
    private static final int PROBEADDRESS = 4;

    private byte[] mReduceProbeReg = new byte[]{0, 0, 0, 0};
    private byte[] mAddProbeReg = new byte[]{1, 0, 0, 0};
    private byte[] mClearData = new byte[]{0, 0};
    private String mUdid = null;

    public IOTProbe(long aDevID, IOTDeviceInfoEx aDeviceInfo, int aStateAddress, int aStateSize) {
        super(aDevID, aDeviceInfo, aStateAddress, aStateSize);
    }

    @Override
    protected void setStateAddress(int aStateAddress) {
        super.setStateAddress(aStateAddress);
        mDefIndex = 1;
    }

    @Override
    public void updateRegister(int aAddress, int aSize, byte[] aData, int aDataPos, int aNetWork, long time) {
        saveRegister(aAddress, aSize, aData, aNetWork);
        LoggerUtil.e("PROBE", "RegData[" + (aNetWork == IOTNetAPIEnum.EIOT_NETWORK_TYPE.EIOT_NETWORK_TYPE_LOCAL ?
                "LOCAL" : "REMOTE") + "]:" + getID() + ", " + aAddress + ", " + aSize + ", " + Arrays.toString(Arrays.copyOf(aData, aSize)));
        //更新寄存器信息
        //aAddress 起始位
        //aData 完整的数据
        if (aData != null && aData.length > 0) {
            int length = aData.length;
            int index = 0;
            if (aAddress == 0 && aData.length >= PROBEADDRESS) { // 返回的数据是从地址0开始的， 就四个四个字节处理不用循环这么多次
                for (int i = 0; i < length; i += PROBEADDRESS) {
                    if (aData[i] > 0) {
                        byte[] newData = Arrays.copyOfRange(aData, i, i + PROBEADDRESS);
                        if (newData != null) {
                            SingleProbe probe = null;
                            probe = mProbes.get(index);
                            if (probe == null) {
                                mProbes.put(index, new SingleProbe(newData, i + BASEADDRESS));
                            } else {
                                probe.setRegDatas(newData);
                                if (mOnTriggerChangedListener != null) {
                                    mOnTriggerChangedListener.onTriggerChange(getAllRegDataCount());
                                }
                            }
                        }
                    } else {
                        mProbes.remove(index);
                    }
                    index++;
                }
            } else {
                aAddress = aAddress - BASEADDRESS;
                for (int i = aAddress; i < aData.length + aAddress; i++) { // 返回的数据是没有规律的, 就只能一个一个字节处理
                    index = i % PROBEADDRESS;
                    SingleProbe probe = mProbes.get(i / PROBEADDRESS);
                    if (index == 0) {
                        if (probe == null && aData[i - aAddress] > 0) {
                            probe = new SingleProbe(null, (i / PROBEADDRESS) * 4 + BASEADDRESS);
                            mProbes.put(i / PROBEADDRESS, probe);
                        } else if (probe != null && aData[i - aAddress] <= 0) {
                            mProbes.remove(i / PROBEADDRESS);
                            probe = null;
                        }
                    }

                    if (probe != null) {
                        byte[] regDatas = probe.getRegDatas();
                        regDatas[index] = aData[i - aAddress];
                        probe.setRegDatas(regDatas);
                        if (mOnTriggerChangedListener != null) {
                            mOnTriggerChangedListener.onTriggerChange(getAllRegDataCount());
                        }
                    }
                }
            }
        }

        if (mListeners != null && mListeners.size() > 0) {
            for (OnRegDataChangedListener listener : mListeners) {
                listener.onRegDataChange();
            }
        }

    }

    @Override
    public String[] getStateIDs() {
        return null;
    }

    /**
     * 获取探头集合
     *
     * @return
     */
    public Map<Integer, SingleProbe> getProbes() {
        return mProbes;
    }

    /**
     * 按顺序创建一个探头
     *
     * @return
     */
    public int addProbe() {
        Set<Integer> keySet = mProbes.keySet();
        for (int i = 0; i < 16; i++) {
            if (!keySet.contains(i)) {
                addProbe((i * PROBEADDRESS) + BASEADDRESS);
                return i;
            }
        }
        return -1;
    }

    /**
     * 不按顺序创建探头
     *
     * @param address 创建探头处的寄存器地址
     */
    private void addProbe(int address) {
        iRegisterInterface.writeRegister(this, address, mAddProbeReg.length, mAddProbeReg, 2);
    }

    /**
     * 按顺序删除探头
     */
    public void reduceProbe() {
        if (mProbes.size() > 0) {
            Set<Integer> keySet = mProbes.keySet();
            reduceProbe((Integer) keySet.toArray()[keySet.size() - 1]);
        }
    }

    /**
     * 不按顺序删除探头
     *
     * @param index 探头在集合中的key
     */
    public void reduceProbe(int index) {
        index = (index * PROBEADDRESS) + BASEADDRESS;
        iRegisterInterface.writeRegister(this, index, mReduceProbeReg.length, mReduceProbeReg, 2);
    }

    @Override
    public int getCornerId() {
        return R.drawable.icon_bg;
    }

    public interface OnRegDataChangedListener {
        public void onRegDataChange();
    }

    private ArrayList<OnRegDataChangedListener> mListeners;

    public void addOnRegDataChangedListener(OnRegDataChangedListener listener) {
        if (mListeners == null) {
            mListeners = new ArrayList<>();
        }
        mListeners.add(listener);
    }

    public void removeOnRegDataChangedListener(OnRegDataChangedListener listener) {
        if (mListeners != null && mListeners.size() > 0) {
            mListeners.remove(listener);
        }
    }

    /**
     * 设置名字
     */
    public boolean setName(long aIndex, String aName) {
        int tmp = mDefIndex;
        mDefIndex = (int) (aIndex + 2);
        boolean result = super.setName(aName);
        mDefIndex = tmp;
        return result;
    }

    /**
     * 设置图标
     */
    public boolean setIcon(long aIndex, String icon) {
        int tmp = mDefIndex;
        mDefIndex = (int) (aIndex + 2);
        boolean result = super.setIcon(icon);
        mDefIndex = tmp;
        return result;
    }

    /**
     * 根据下表获取名字
     *
     * @param index
     * @return
     */
    public String getName(int index) {
        int tmp = mDefIndex;
        mDefIndex = index + 1;
        String name = super.getName();
        mDefIndex = tmp;
        return name;
    }

    /**
     * 根据下表获取图片
     *
     * @param index
     * @return
     */
    public int getIcon(int index) {
        int tmp = mDefIndex;
        mDefIndex = index + 1;
        int icon = super.getSplitIconId();
        mDefIndex = tmp;
        return icon;
    }

    @Override
    public boolean isHide() {
        return super.isHide();
    }

    /**
     * 获取探头的寄存器地址
     *
     * @param position
     * @return
     */
    public int getProbeAddress(int position) {
        return PROBEADDRESS * position + BASEADDRESS;
    }

    /**
     * 探头控制界面初始化时需要获取所有探头的触发数据, 通过address和size来匹配
     *
     * @param time    时间
     * @param address 地址
     * @param size    长度
     * @param data    数据
     * @param refid   链表
     * @return
     */
    public boolean setTime(String time, int address, int size, byte[] data, long refid) {

        int index = 0;
        int tmp = -1;
        int iAddress = address - BASEADDRESS;
        for (int i = 0; i < size; i++) {
            index = iAddress / PROBEADDRESS;
            if (index != tmp) {
                SingleProbe probe = mProbes.get(index);
                if (probe != null && probe.getTimeDataCount() < 20) {
                    probe.addTimeData(time, refid);
                }
                tmp = index;
            }
            iAddress++;
        }

        return timeDataIsFull();
    }

    /**
     * 初始化时需要每个探头都获取到20条触发信息, 检查是否已经全部初始化完毕
     *
     * @return
     */
    public boolean timeDataIsFull() {
        Set<Integer> keySet = mProbes.keySet();
        boolean isContinue = true;
        for (Integer key : keySet) {
            SingleProbe probe = mProbes.get(key);
            if (probe != null/* && probe.getRegDatas()[1] > 0*/) {
                //				int count = ((0xffffffff & probe.getRegDatas()[3]) << 8) | (0xff & probe.getRegDatas()[2]);
                isContinue = (probe.getTimeDataCount() >= 20)/* || (probe.getTimeDataCount() >= count)*/;
                if (!isContinue) {
                    break;
                }
            }
        }

        return !isContinue;
    }

    /**
     * 清空所有探头的触发信息
     */
    public void clearTimeData() {
        Set<Integer> keySet = mProbes.keySet();
        for (Integer integer : keySet) {
            mProbes.get(integer).cleanTimeData();
        }
    }

    public void clearProbeTimeData(int index) {
        SingleProbe singleProbe = mProbes.get(index);
        if (singleProbe != null) {
            iRegisterInterface.writeRegister(this, singleProbe.getAddress() + 2, 2, mClearData, 2);
        }
    }

    public int getAllRegDataCount() {
        Set<Integer> integers = mProbes.keySet();
        int count = 0;
        for (Integer regIndex : integers) {
            SingleProbe singleProbe = mProbes.get(regIndex);
            if (singleProbe != null) {
                count += singleProbe.getTriggerCount();
            }
        }
        return count;
    }

    @Override
    public int getRegisterAddress() {
        return super.getRegisterAddress() + BASEADDRESS;
    }

    @Override
    public String getUDID() {
        if (mUdid == null) {
            mUdid = super.getUDID().replace('-', '@');
        }
        return mUdid;
    }

    private OnTriggerChangeListener mOnTriggerChangedListener = null;

    public void setOnTriggerChangeListener(OnTriggerChangeListener l) {
        mOnTriggerChangedListener = l;
    }

    public interface OnTriggerChangeListener {
        public void onTriggerChange(int count);
    }

    @Override
    public int getImageId() {
        return R.drawable.icon_probe;
    }


    /**
     * 获取图片的id
     *
     * @param probeIndex
     * @return
     */
    public String getImageID(int probeIndex) {
        return "DEV." + getUDID() + "." + probeIndex;
    }


    public boolean setImage(int probeIndex, Bitmap bitmap) {

        //状态图片id
        String imageID = getImageID(probeIndex);
        if (bitmap == null) {
            if (ImageManager.RemoveBitmap(imageID)) {
                return true;
            }
        } else {
            ImageManager.SetBitmap(imageID, bitmap);
            return true;
        }
        return false;
    }

    @Override
    public boolean setImage(Bitmap image) {
        return setImage(zoneIndex, image);
    }


    public Bitmap getImage(int probeIndex) {
        if (getImageCount(probeIndex) > 0) {
            String imageID = getImageID(probeIndex);
            return ImageManager.GetBitmap(imageID);
        }
        return null;
    }

    @Override
    public Bitmap getImage() {
        return getImage(zoneIndex);
    }

    public int getImageCount(int zoneIndex) {
        String imageID = getImageID(zoneIndex);
        if (ImageManager.ContainsBitmap(imageID)) {
            return 1;
        }
        return 0;
    }
}
